<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <i class="el-icon-search btn-search" @click="handleShowSearch()" />
      <div class="btn-box">  <el-button type="primary" @click="handleaddUser()">添加用户</el-button></div>
      <div v-show="showbtns==true" class="search-lf">
        <el-form-item label="用户名">
          <el-input v-model="listQuery.name" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="listQuery.memberName" placeholder="账号" />
        </el-form-item>

        <el-form-item label="是否禁用">
          <el-select v-model="listQuery.state" filterable placeholder="是否禁用">
            <el-option label="是" value="0" />
            <el-option label="否" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="getList()">查询</el-button>

        </el-form-item>
      </div>

    </el-form>
    <el-table
      v-loading="listLoading"
      border
      height="650px"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" width="60px" label="序号">
        <template slot-scope="scope">
          <span>{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="用户名">
        <template slot-scope="{row}">
          <span>{{ row.memberName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否禁用">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.state"
            active-color="#d9d9d9"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleState(row)"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" label="战区">
        <template slot-scope="{row}">
          <el-tag>{{ row.regionName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="省份">
        <template slot-scope="{row}">
          <el-tag>{{ row.provinceName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="220">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            :disabled="editDisabled==true"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >编辑</el-button>

          <el-button
            class="mg-l"
            type="warning"
            size="mini"
            icon="el-icon-setting"
            @click="handlePerssion(row)"
          >分配</el-button>
          <el-button
            class="mg-l"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDel(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'添加用户'" @close="handleClose">
      <el-form ref="usersList" label-width="80px" :model="usersList" label-position="left">
        <el-form-item label="用户账号">
          <el-input v-model="usersList.memberName" placeholder="请输入用户账号" />
        </el-form-item>

        <el-form-item label="真实姓名">
          <el-input v-model="usersList.name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="usersList.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="usersList.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="usersList.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="战区">
          <el-select
            v-model="usersList.regionName"
            filterable
            placeholder="请选择"
            @change="handleChangeRegio($event)"
          >
            <el-option
              v-for="item in RegionList"
              :key="item.regionId"
              :label="item.region"
              :value="item.region"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省份">
          <el-select
            v-model="usersList.provinceName"
            filterable
            placeholder="请选择"
            @change="handleChangePro($event)"
          >
            <el-option
              v-for="item in rgionProList"
              :key="item.provinceId"
              :label="item.provinceName"
              :value="item.provinceName"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button type="primary" @click="confirmRole">确定</el-button>
        <el-button type="danger" class="cancel_border" plain @click="dialogVisible=false;editDisabled=false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleMenu" title="角色分配">
      <el-form label-width="80px" label-position="left">
        <el-form-item label>
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="rolesData"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            :default-expanded-keys="defaultExpandKey"
            :default-checked-keys="defaultExpandKey"
            class="permission-tree"
            @check-change="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisibleMenu=false">取消</el-button>
        <el-button type="primary" @click="confirmRolePerm()">确定</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>=20"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  userList,
  addUser,
  updateUser,
  updateUserState,
  updateUserPermission,
  deleteUser,
  regiosList,
  getUserById
} from '@/api/user'
import { roleList } from '@/api/role'
import { RegionsProvince } from '@/api/region'
import { Message } from 'element-ui'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const defaultRole = {
  key: '',
  name: '',

  roles: []
}
export default {
  name: 'UserList',

  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '男',
        0: '女'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      showbtns: false,
      defaultExpandKey: [],
      defaultChecked: [],
      downloadLoading: false,
      RegionList: [],
      list: [], editDisabled: false,
      rgionProList: [],
      downloadLoading: false,
      usersList: {
        memberName: '', //	用户账号

        password: '', //	用户密码

        name: '', //	真实姓名

        mobile: '', //	用户手机号

        email: '', // 用户邮箱

        sex: '1' // 性别
      },
      total: 0,
      dialogVisibleMenu: false,
      listLoading: true,
      listQuery: {
        access_token: sessionStorage.getItem('token'),
        page: 1,

        name: '',

        state: '',
        pageSize: 20
      },
      roles: [],
      role: Object.assign({}, defaultRole),
      userId: '', // 用户id
      rolesList: [],

      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'childMenu',
        label: 'name'
      },
      ids: ''
    }
  },
  computed: {
    rolesData() {
      return this.roles
    }
  },
  created() {
    this.getList()
    this.getroles()
  },
  methods: {
    handleClose() {
      this.editDisabled = false
    },
    handleShowSearch() {
      this.showbtns = !this.showbtns
    },
    handleChangePro(id) {
      let obj = {}
      obj = this.rgionProList.find((item) => {
        // model就是上面的数据源
        return item.provinceName === id // 筛选出匹配数据
      })

      this.usersList.provinceId = obj.provinceId
    },
    handleChangeRegio(id) {
      let obj = {}
      obj = this.RegionList.find((item) => {
        // model就是上面的数据源
        return item.region === id // 筛选出匹配数据
      })

      RegionsProvince(obj.id).then((res) => {
        this.rgionProList = res.data.data
      })
      this.usersList.regionId = obj.id
    },
    handleState(row) {
      // let data = {
      //   state:
      // };
      updateUserState(row.id, row.state).then((res) => {
        if (res.data.code === '200') {
          this.$message.success(res.data.message)
          this.getList()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getList() {
      this.editDisabled = false

      regiosList().then((res) => {
        this.RegionList = res.data.data
      })

      this.listLoading = true
      userList(this.listQuery)
        .then((response) => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleDel(id) {
      this.$confirm('确定删除该用户么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(() => {
          deleteUser(id).then((res) => {
            if (res.data.code === '200') {
              this.$message.success(res.data.message)
              this.getList()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getroles() {
      roleList(sessionStorage.getItem('token')).then((res) => {
        this.roles = res.data.data.rows
      })
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
    },
    handlePerssion(row) {
      this.dialogVisibleMenu = true

      this.userId = row.id
      getUserById(this.userId).then((res) => {
        const resd = []
        //  resd.push(res.data.data.roles[0].id);
        res.data.data.roles.forEach(item => {
          resd.push(item.id)
        })
        this.defaultExpandKey = resd
        this.$refs.tree.getCheckedNodes()
      })
      // defaultChecked
    },

    confirmRolePerm() {
      this.checkStrictly = true

      const checkedList = this.$refs.tree.getCheckedKeys()
      const res = []
      if (checkedList.length > 0) {
        checkedList.forEach((r) => {
          res.push(r)
        })
        this.ids = res.join(',')
      }

      const data = {
        roleIds: this.ids
      }
      updateUserPermission(this.userId, data).then((res) => {
        if (res.data.code === '200') {
          this.$message.success(res.data.message)
          this.dialogVisibleMenu = false
          this.getList()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleaddUser() {
      this.usersList = {}
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['usersList'].clearValidate()
      })
    },
    handleEdit(row) {
      this.editDisabled = true
      this.dialogType = 'edit'
      this.dialogVisible = true

      this.usersList = row
      this.usersList.password = ''
      this.userId = row.id
    },
    confirmRole(id) {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        updateUser(this.usersList).then((res) => {
          if (res.data.code === '200') {
            this.$message.success(res.data.message)
            this.dialogVisible = false
            this.getList()
            this.editDisabled = false
          } else {
            this.$message.error(res.data.message)
          }
        })
        return false
      }
      const _this = this
      const data = {}

      addUser(this.usersList).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)

          _this.dialogVisible = false
          _this.userList = ''
          _this.getList()
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }

}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
